package com.ilink.ilinkgateway.jwt;

import com.ilink.ilinkcommon.utils.CollUtils;
import com.ilink.ilinkgateway.config.JwtProperties;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <h3>new-ilink-java-backend</h3>
 *
 * @author LiuZheng
 * @description <p>jwt过滤器</p>
 * @date 2024-09-15 12:00
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;

    private final JwtTokenProvider jwtTokenProvider;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * @return boolean
     * @Author LiuZheng
     * @Description 根据白名单判断是否放行token
     * @Date 15:17 2024-09-15
     * @Param [path]
     **/
    private boolean shouldNotFilter(String path) {
        for (String pathPattern : jwtProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return reactor.core.publisher.Mono<java.lang.Void>
     * @Author LiuZheng
     * @Description 过滤器
     * @Date 15:15 2024-09-15
     * @Param [exchange, chain]
     **/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 拦截请求
        log.info("进入jwt过滤器");
        ServerHttpRequest request = exchange.getRequest();

        // 根据白名单判断是否放行
        if (shouldNotFilter(request.getPath().toString())) {
            log.info("放行");
            return chain.filter(exchange);
        }

        // 获取token
        String token = null;
        List<HttpCookie> httpCookies = request.getCookies().get("access_token_lf");
        List<String> headers = request.getHeaders().get("authorization");
        log.info("获取token{}", httpCookies);
        log.info("获取token{}", headers);
        if (!CollUtils.isEmpty(httpCookies)) {
            for (HttpCookie cookie : httpCookies) {
                if (cookie.getName().equals("access_token_lf")) {
                    token = cookie.getValue();
                }
            }
            log.info("获取token{}", token);
        } else {
            // 拦截
            log.info("被拦截");
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //  解析token正确性      
        try {
            jwtTokenProvider.validateToken(token);
        } catch (Exception e) {
            // 拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        // 传递token中携带的用户信息
        String userId = jwtTokenProvider.getUserIdFromToken(token);
        ServerWebExchange swe = exchange.mutate()
            .request(builder -> builder.header("userId", userId))
            .build();

        // 进入下一个过滤器
        return chain.filter(swe);
    }
}
